<?php
declare (strict_types=1);

namespace addons\BuilderPlus\contract\model;

use app\common\model\Base;

class Crontab extends Base
{
    protected $type = [
        'last_time' => 'timestamp',
    ];

    protected function getUrladdressAttr($value): string
    {
        return request()->domain() . $value;
    }

    public static function _save($param, $options): array
    {
        try {
            $param['addtime'] = date('Y-m-d H:i:s');
            if (!empty($param['id'])) {
                parent::update($param, ['id' => $param['id']]);
            } else {
                parent::create($param);
            }

            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _export($param): array
    {
        $list = parent::withoutField('tips,last_time,delete_time')->select();
        foreach ($list as &$item) {
            $item->sType = 'toUrl';
            switch ($item->type) {
                case 'second-n':
                    $item->type = 'second';
                    $item->flock = 0;
                    break;
                case "hour-n":
                    $item->where_hour = $item->where1;
                    break;
                case "minute-n":
                    $item->where_minute = $item->where1;
                    break;
            }
        }
        $folderPath = '/download';
        $filePath = $folderPath . '/计划任务.json';
        if (!file_exists('.' . $folderPath)) {
            mkdir('.' . $folderPath, 0777, true);
        }
        if (file_put_contents('.' . $filePath, $list->toJson()) === false) {

            return ['code' => -1, 'msg' => '导出失败，请检查download文件夹权限'];
        } else {

            return ['code' => 1, 'msg' => '正在导出', 'data' => $filePath, 'type' => 'json', 'title' => '计划任务.json'];
        }
    }
}